/*
  Config file viewer 2.0
  By DreamVB Simple project to load a custom configuration file into your program.
*/

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>

using namespace std;
using std::cout;
using std::endl;

//Holds all the configuration data.
vector<string>cfg_data;

string TrimR(string src){
	// trim trailing spaces
	size_t endpos = src.find_last_not_of(" \t");
	if (string::npos != endpos)
	{
		src = src.substr(0, endpos + 1);
	}
	return src;
}

string TrimL(string src){
	// trim leading spaces
	size_t startpos = src.find_first_not_of(" \t");
	if (string::npos != startpos)
	{
		src = src.substr(startpos);
	}
	return src;
}

string TrimAll(string src){
	return TrimL(TrimR(src));
}

string ReadValue(string Index){
	int i = 0;
	int pos = 0;
	string Key = "";
	string sLine = "";

	while (i < cfg_data.size()){
		//Trim leading and trailing spaces.
		sLine = TrimAll(cfg_data[i]);
		//Check length, Check line not empty and check for comments.
		if ((sLine.length() > 1) && 
			(sLine[0] != '\r') && (sLine[0] != '#')){
			//Find first space
			pos = sLine.find_first_of(" ");
			//Check that space was found.
			if (pos != string::npos){
				//Extract the key
				Key = TrimAll(sLine.substr(0, pos));
				//Compare Key with input key
				if (strcmp(Key.c_str(), Index.c_str())==0){
					//Return value of key
					return TrimAll(sLine.substr(pos));
					break;
				}
			}
		}
		//Keep counter going.
		i++;
	}
	return "";
}

int main(int argc, char *argv[]){

	fstream fs;
	string StrLine = "";

	//Check args
	if (argc != 2){
		cout << "Usage: " << argv[0] << " <filename>" << endl;
		exit(1);
	}

	system("title Configuration Viewer");

	//Try and open the file.
	fs.open(argv[1], ios::in | ios::binary);
	
	//Has file loaded ?
	if (!fs.good()){
		exit(1);
	}

	//While data in file read in a line
	while (getline(fs, StrLine)){
		//Push line onto vector.
		cfg_data.push_back(StrLine);
	}

	//Close file
	fs.close();

	cout << "Configuration file viewer" << endl;
	cout << endl;
	cout << "Name        : " << ReadValue("NAME") << endl;
	cout << "AGE         : " << ReadValue("AGE") << endl;
	cout << "HEIGHT      : " << ReadValue("HEIGHT") << endl;
	cout << "POSITION    : " << ReadValue("JOB") << endl;

	//Clear up.
	cfg_data.clear();
	
	return 0;
}